<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores'
import { sendWeChatLoginCodeAPI } from '@/api/user'

// 初始化store
const userStore = useUserStore()

// 获取用户信息
const username = ref(userStore.userInfo?.username || '游客')
const avatarUrl = ref(userStore.avatarUrl || '/static/images/default.png')

// 微信登录
const handleWechatLogin = async () => {
  // 1. 先询问用户是否同意使用微信登录
  const confirmLogin = await new Promise((resolve) => {
    uni.showModal({
      title: '微信登录',
      content: '是否允许使用微信账号登录本应用?',
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        resolve(res.confirm) // 返回用户是否确认
      },
    })
  })

  // 如果用户取消，则不执行登录
  if (!confirmLogin) {
    return
  }

  // 2. 用户同意后，再执行登录流程
  try {
    // 获取 code（原有逻辑）
    const loginRes = await new Promise((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: resolve,
        fail: reject,
      })
    })

    // 发送code到后端（原有逻辑）
    const res = await sendWeChatLoginCodeAPI(loginRes.code)

    // 检查登录是否成功（原有逻辑）
    if (res.code === 1 && res.data) {
      await userStore.loginAction(res.data.token, res.data.id)

      // 更新本地显示的用户信息（原有逻辑）
      username.value = userStore.userInfo?.username || '微信用户'
      avatarUrl.value = userStore.userInfo?.avatarUrl || avatarUrl.value

      uni.showToast({ title: '登录成功' })
    } else {
      throw new Error(res.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    uni.showToast({
      title: error.message || '登录失败',
      icon: 'none',
      duration: 2000,
    })
  }
}

// 退出登录
const logout = () => {
  uni.showModal({
    title: '温馨提示🥹',
    content: '您确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        //手动更新页面的响应式变量
        username.value = '游客'
        userStore.avatarUrl = '/static/images/default.png'

        // 清除用户信息和登录状态
        userStore.logout()
        uni.showToast({
          title: '已成功退出登录',
          icon: 'success',
        })
      }
    },
  })
}

// 页面跳转函数
const goToCollect = () => {
  uni.navigateTo({
    url: '/pages/Collect/index',
  })
}

const goToFeedback = () => {
  uni.navigateTo({
    url: '/pages/Feedback/index',
  })
}

const goToEditProfile = () => {
  uni.navigateTo({
    url: '/pages/EditInfo/index',
  })
}

const goToAbout = () => {
  uni.navigateTo({
    url: '/pages/AboutUs/index',
  })
}

onShow(() => {
  if (userStore.isLoggedIn) {
    userStore
      .getUserInfo()
      .then(() => {
        // 更新本地显示的用户信息
        username.value = userStore.userInfo?.username || '微信用户'
        avatarUrl.value = userStore.avatarUrl || '/static/images/default.png'
      })
      .catch((err) => {
        console.error('获取用户信息失败:', err)
      })
  }
})
</script>
<template>
  <view class="profile-container">
    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="avatar-container">
        <image :src="avatarUrl" mode="aspectFill" class="avatar" />
        <view class="avatar-ring"></view>
      </view>
      <text class="username">{{ username }}</text>
      <view v-if="!userStore.isLoggedIn" class="login-section">
        <view class="login-btn wechat-btn" @tap="handleWechatLogin">
          <text class="login-text">去登录</text>
          <text class="iconfont icon-arrow"></text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-group">
        <text class="group-title">个人中心</text>
        <view class="menu-item" @tap="goToCollect">
          <text class="iconfont icon-caipin- menu-icon"></text>
          <text class="menu-text">收藏菜品</text>
          <text class="iconfont icon-arrow menu-arrow"></text>
        </view>
        <view class="menu-item" @tap="goToFeedback">
          <text class="iconfont icon-banshou menu-icon"></text>
          <text class="menu-text">服务与反馈</text>
          <text class="iconfont icon-arrow menu-arrow"></text>
        </view>
        <view class="menu-item" @tap="goToEditProfile">
          <text class="iconfont icon-tianxie menu-icon"></text>
          <text class="menu-text">编辑信息</text>
          <text class="iconfont icon-arrow menu-arrow"></text>
        </view>
        <view class="menu-item logout-item" @tap="logout">
          <text class="iconfont icon-tuichudenglu menu-icon"></text>
          <text class="menu-text">退出登录</text>
          <text class="iconfont icon-arrow menu-arrow"></text>
        </view>
      </view>
    </view>

    <!-- 关于我们 -->
    <view class="about-section">
      <text class="about-link" @tap="goToAbout">关于我们</text>
    </view>
  </view>
</template>

<style scoped lang="scss">
.profile-container {
  height: 97.1vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 40rpx 32rpx 0 32rpx;
  overflow-y: auto;
}

// 用户信息卡片
.user-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 40rpx;
  padding: 60rpx 40rpx;
  text-align: center;
  margin-bottom: 20rpx;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.1);
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  position: relative;
  overflow: hidden;

  .avatar-container {
    position: relative;
    display: inline-block;
    margin-bottom: 32rpx;

    .avatar {
      width: 160rpx;
      height: 160rpx;
      border-radius: 50%;
      border: 6rpx solid rgba(102, 126, 234, 0.2);
      transition: all 0.3s ease;
    }

    .avatar-ring {
      position: absolute;
      top: -6rpx;
      left: -6rpx;
      right: -6rpx;
      bottom: -6rpx;
      border: 4rpx solid transparent;
      border-radius: 50%;
      background: linear-gradient(45deg, #667eea, #764ba2);
      opacity: 0;
      animation: rotate 3s linear infinite;
    }
  }

  .username {
    font-size: 48rpx;
    font-weight: 600;
    color: #333;
    margin: 0 0 16rpx 0;
    background: linear-gradient(45deg, #667eea, #764ba2);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    display: block;
  }

  .user-info {
    color: #666;
    font-size: 28rpx;
    margin: 0;
    opacity: 0.8;
    display: block;
  }

  .login-prompt {
    display: inline-flex;
    align-items: center;
    gap: 16rpx;
    background: linear-gradient(45deg, #667eea, #764ba2);
    color: white;
    padding: 16rpx 32rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
    margin: 0;

    .login-text {
      font-size: 28rpx;
    }

    .iconfont {
      font-size: 24rpx;
      transition: transform 0.3s ease;
    }
  }

  .login-section {
    display: flex;
    justify-content: center;
    margin-top: 16rpx;

    .login-btn {
      display: inline-flex;
      align-items: center;
      gap: 12rpx;
      padding: 20rpx 40rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);

      .iconfont {
        font-size: 28rpx;
      }

      .login-text {
        font-size: 28rpx;
      }

      &.wechat-btn {
        background: linear-gradient(45deg, #667eea, #764ba2);
        color: white;

        &:active {
          transform: translateY(2rpx);
          box-shadow: 0 6rpx 20rpx rgba(102, 126, 234, 0.4);
        }
      }
    }
  }
}

// 菜单区域
.menu-section {
  .menu-group {
    margin-bottom: 0;

    .group-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin: 0 0 24rpx 32rpx;
      opacity: 0.8;
      display: block;
    }

    .menu-item {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(20px);
      border-radius: 32rpx;
      padding: 32rpx 40rpx;
      margin-bottom: 16rpx;
      display: flex;
      align-items: center;
      cursor: pointer;
      transition: all 0.3s ease;
      box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);

      &:last-child {
        margin-bottom: 0;
      }

      .menu-icon {
        font-size: 40rpx;
        color: #667eea;
        margin-right: 32rpx;
        width: 48rpx;
        text-align: center;
      }

      .menu-text {
        flex: 1;
        font-size: 32rpx;
        color: #333;
        font-weight: 500;
      }

      .menu-arrow {
        font-size: 28rpx;
        color: #999;
        transition: transform 0.3s ease;
      }

      // 退出登录特殊样式
      &.logout-item {
        .menu-icon {
          color: #ff6b6b;
        }

        .menu-text {
          color: #ff6b6b;
        }
      }
    }
  }
}

// 关于我们
.about-section {
  text-align: center;
  padding: 80rpx 0 0 0;

  .about-link {
    color: rgba(0, 0, 0, 0.8);
    text-decoration: none;
    font-size: 28rpx;
    opacity: 0.8;
    transition: all 0.3s ease;
  }
}

// 动画
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 小程序样式适配 */
/* #ifdef MP-WEIXIN */
.user-card {
  background: rgba(255, 255, 255, 0.98) !important;
  backdrop-filter: none !important;
  border: 2rpx solid #f0f0f0 !important;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.08) !important;
}

.menu-item {
  background: rgba(255, 255, 255, 0.98) !important;
  backdrop-filter: none !important;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.06) !important;
}

.username {
  color: #667eea !important;
  background: none !important;
  background-clip: unset !important;
  -webkit-background-clip: unset !important;
  -webkit-text-fill-color: unset !important;
}
/* #endif */

/* H5样式优化 */
/* #ifdef H5 */
.user-card {
  backdrop-filter: blur(20px) !important;
}

.menu-item {
  backdrop-filter: blur(20px) !important;
}

.username {
  background: linear-gradient(45deg, #667eea, #764ba2) !important;
  background-clip: text !important;
  -webkit-background-clip: text !important;
  -webkit-text-fill-color: transparent !important;
}
/* #endif */

// 平板适配
@media (min-width: 768px) {
  .profile-container {
    max-width: 1200rpx;
    margin: 0 auto;
    padding-bottom: 80rpx;
  }

  .user-card {
    padding: 80rpx 60rpx;

    .username {
      font-size: 56rpx;
    }
  }

  .menu-section .menu-group .menu-item {
    padding: 40rpx 48rpx;
    border-radius: 40rpx;

    .menu-text {
      font-size: 36rpx;
    }
  }
}
</style>
